package com.holic.spring.custom.config;

import com.holic.spring.custom.fetcher.DoSomeThing;
import com.holic.spring.custom.fetcher.DynamicMethodDataFetcher;
import com.holic.spring.custom.fetcher.GetUserFetcher;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;

/**
 * @ClassName GraphQLConfig
 * @Description
 * @Author Neil
 * @Date 2024/11/12 16:21
 * @Version V1.0
 **/
@Configuration
public class GraphQLConfig {


    @Bean
    public GraphQLSource graphQL() throws IOException {
        // 读取GraphQL Schema文件
//        ClassPathResource resource = new ClassPathResource("graphql/project.graphqls");
//        TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(resource.getInputStream());
//        RuntimeWiring wiring = buildWiring();
//        GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(typeRegistry, wiring);
//        GraphQL graphQL = GraphQL.newGraphQL(schema).build();

        GraphQLSource source = new GraphQLSource();
//        source.setGraphQL(graphQL);

//        new Thread(()->{
//            while(true){
//                try {
//                    Thread.sleep(3000);
//                    RuntimeWiring newwiring = RuntimeWiring.newRuntimeWiring()
//                            .type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("Hello, World!")))
//                            .type("Query", builder -> builder.dataFetcher("user", new GetUserFetcher()))
//                            .type("Mutation", builder -> builder.dataFetcher("doSomeThing1", new DoSomeThing()))
//                            .build();
//                    GraphQLSchema newschema = new SchemaGenerator().makeExecutableSchema(typeRegistry, newwiring);
//                    GraphQL newInstance = GraphQL
//                            .newGraphQL(newschema)
//                            .build();
//                    source.setGraphQL(newInstance);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        }).start();
        return source;
    }

    private RuntimeWiring buildWiring() {
        return RuntimeWiring.newRuntimeWiring()
                .type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("Hello, World!")))
                .build();
    }
}
